﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ECSE6770.Controllers
{
    [RequireHttps]
    [Authorize(Roles = "Admin")]
    public class ModuleController : BaseAdminController
    {
        public ActionResult Index()
        {
            DateTime now = DateTime.Now;
            ViewBag.IntroHtml = String.Format("Upcoming Modules | <a href=\"{0}\">Past Modules</a>", Url.Action("Past", "Module"));
            return View(Db.Modules.Where(m => m.End > now).OrderBy(m => m.Title));
        }

        public ActionResult Past()
        {
            DateTime now = DateTime.Now;
            ViewBag.IntroHtml = String.Format("<a href=\"{0}\">Upcoming Modules</a> | Past Modules", Url.Action("Index", "Module"));
            return View("Index", Db.Modules.Where(m => m.End < now).OrderBy(m => m.Title));
        }

        public ActionResult New()
        {
            return View("Edit", null);
        }

        public ActionResult Edit(int id)
        {
            return View(Db.Modules.First(m => m.Id == id));
        }

        [HttpPost]
        public ActionResult Edit(Module model)
        {
            if (ModelState.IsValid)
            {
                model.DatePosted = DateTime.Now;
                if (model.Id == 0)
                {
                    model.Deleted = false;
                    model.BindReferences(Db);
                    Db.Products.Add(model);
                    Db.SaveChanges();

                    return Success("Create New Module", "Your module has been successfully created.", "View All Modules", Url.Action("Index", "Module"));
                }
                else
                {
                    Db.Entry(model).State = System.Data.EntityState.Modified;
                    model.CheckModifiedReferences(Db);
                    Db.SaveChanges();
                    return Success("Edit Module", "Your module has been successfully modified.", "View All Modules", Url.Action("Index", "Module"));
                }
            }
            else
                return View();
        }

        public ActionResult Delete(int id)
        {
            var module = Db.Modules.First(m => m.Id == id);
            
            //jump through a bunch of hoops to make entity framework actually work...
            module.SpeakerUserNames = new List<string>();

            module.Deleted = true;
            Db.SaveChanges();
            return Success("Module Deleted", String.Concat(module.Title, " has been successfully deleted."), "View All Modules", Url.Action("Index", "Module"));
        }
    }
}
